<template>
    <div class="app-container">
        <div class="search-container">
            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="queryParams.configName" clearable placeholder="请输入参数名称"
                              @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="参数键名" prop="configKey">
                    <el-input v-model="queryParams.configKey" clearable placeholder="请输入参数键名"
                              @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="系统内置" prop="configType">
                    <el-radio-group v-model="queryParams.configType" @change="handleQuery">
                        <el-radio value="">全部</el-radio>
                        <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                                  :value="dict.dictValue">{{
                                dict.dictLabel
                            }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <div class="mr20" style="float: right">
                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                </div>
            </el-form>
        </div>
        <el-row :gutter="10" class="mb8" style="margin-right: 180px">
            <el-col :span="1.5">
                <el-button plain type="primary" @click="handleAdd">
                    <template #icon>
                        <i-ep-plus/>
                    </template>
                    新增
                </el-button>
            </el-col>
<!--            <el-col :span="1.5">-->
<!--                <el-button :disabled="multiple" plain type="danger"-->
<!--                           @click="handleDelete">-->
<!--                    <template #icon>-->
<!--                        <i-ep-delete/>-->
<!--                    </template>-->
<!--                    删除-->
<!--                </el-button>-->
<!--            </el-col>-->
<!--            <el-col :span="1.5">-->
<!--                <el-button v-hasPerm="['system:config:remove']" plain type="danger"-->
<!--                           @click="handleRefreshCache">-->
<!--                    <template #icon>-->
<!--                        <i-ep-refresh/>-->
<!--                    </template>-->
<!--                    刷新缓存-->
<!--                </el-button>-->
<!--            </el-col>-->
        </el-row>

        <el-table v-adaptive="300" :border="true" :data="configList" :header-cell-style="$headerCellStyle" :stripe='true'
                  highlight-current-row @selection-change="handleSelectionChange">
            <el-table-column :align="'center'" type="selection" width="55"/>
            <el-table-column :header-align="'center'" :show-overflow-tooltip="true" label="参数名称" prop="configName"/>
            <el-table-column :header-align="'center'" :show-overflow-tooltip="true" label="参数键名" prop="configKey"/>
            <el-table-column :header-align="'center'" :show-overflow-tooltip="true" label="参数键值"
                             prop="configValue"/>
            <el-table-column :header-align="'center'" :show-overflow-tooltip="true" label="备注" prop="remark"/>
            <el-table-column :align="'center'" label="创建时间" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ $parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="220">
                <template #default="scope">
                    <el-button  type="success"
                               @click="handleUpdate(scope.row)">
                        <template #icon>
                            <i-ep-edit/>
                        </template>
                        修改
                    </el-button>
<!--                    <el-button v-hasPerm="['system:config:remove']" type="danger"-->
<!--                               @click="handleDelete(scope.row)">-->
<!--                        <template #icon>-->
<!--                            <i-ep-delete/>-->
<!--                        </template>-->
<!--                        删除-->
<!--                    </el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList('')"/>

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="600px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="form.configName" placeholder="请输入参数名称"/>
                </el-form-item>
                <el-form-item label="参数键名" prop="configKey">
                    <el-input v-model="form.configKey" placeholder="请输入参数键名"/>
                </el-form-item>
                <el-form-item label="参数键值" prop="configValue">
                    <el-input v-model="form.configValue" autosize placeholder="请输入参数键值" type="textarea"/>
                </el-form-item>
                <el-form-item label="系统内置" prop="configType">
                    <el-radio-group v-model="form.configType">
                        <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                                  :value="dict.dictValue">{{
                                dict.dictLabel
                            }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {addConfig, delConfig, getConfig, listConfig, refreshCache, updateConfig} from "@/api/system/configPerson";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";

const useUserStore = useUserStoreHook();
const clinicScheduleTableRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const formRef = ref()
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('sys_yes_no'))
const {proxy} = getCurrentInstance() as any
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 参数表格数据
const configList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 日期范围
const dateRange = ref([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dictType: undefined,
    status: '',
    systemType: '',
    userId: userInfo.userId,
    orgId: userInfo.orgId
})
// 表单参数
const form = ref<any>({
    userId: userInfo.userId,
    orgId: userInfo.orgId
})
// 表单校验
const rules = ref({
    configName: [
        {required: true, message: "参数名称不能为空", trigger: "blur"}
    ],
    configKey: [
        {required: true, message: "参数键名不能为空", trigger: "blur"}
    ],
    configValue: [
        {required: true, message: "参数键值不能为空", trigger: "blur"}
    ]
})
getList("")

/** 查询参数列表 */
function getList(type) {
    listConfig(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
            configList.value = response.rows;
            total.value = response.total;
            if (type ==="1") {
                useUserStore.setConfigPersonList(response.rows)
            }
        }
    );
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        configId: undefined,
        configName: undefined,
        configKey: undefined,
        configValue: undefined,
        configType: "Y",
        remark: undefined,
        userId: userInfo.userId,
        orgId: userInfo.orgId
    };
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList("");
}

/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    dateRange.value = [];
    handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加参数";
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.configId)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const configId = row.configPersonId || ids.value
    getConfig(configId).then((response: any) => {
        form.value = response.data;
        open.value = true;
        title.value = "修改参数";
    });
}

/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            if (form.value.configPersonId != undefined) {
                updateConfig(form.value).then(() => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList("1");
                });
            } else {
                addConfig(form.value).then(() => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList("1");
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const configIds = row.configId || ids.value;
    ElMessageBox.confirm('是否删除选中的数据项？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        delConfig(configIds).then(() => {
            getList("1");
            ElMessage.success("删除成功");
        })
    }).catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
    // this.download('system/config/export', {
    //     ...this.queryParams
    // }, `config_${new Date().getTime()}.xlsx`)
}

/** 刷新缓存按钮操作 */
function handleRefreshCache() {
    refreshCache().then(() => {
        ElMessage.success("刷新成功");
    });
}
</script>
<script lang="ts">
export default {
    name: "Config"
}
</script>
<style>
.el-tooltip__popper {
    max-width: 25%;
}
</style>
